<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="'/home'">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入姓名" v-model="searchInputValue" @keyup.enter.native="loadUserList()">
            <el-button slot="append" icon="el-icon-search" @click="loadUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialog.visible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="users" stripe border>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="80">
          <template slot-scope="slotProps">
            <el-switch :value="slotProps.row.mg_state" @change="onSateChange($event, slotProps.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="slotProps">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="toEditUser(slotProps.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(slotProps.row)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showAssignRoleDialog(slotProps.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        :page-size="pageInfo.pagesize"
        :page-sizes="[1, 2, 5, 10]"
        @current-change="onPagenumChange($event)"
        @size-change="onPagesizeChange($event)"
      ></el-pagination>
    </el-card>

    <el-dialog title="添加用户" :visible.sync="addUserDialog.visible" width="30%" @close="onAddUserDialogClose()">
      <div>
        <el-form ref="addUserForm" :model="addUserDialog.formData" :rules="addUserDialog.formRules" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserDialog.formData.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserDialog.formData.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserDialog.formData.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserDialog.formData.mobile"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑用户" :visible.sync="editUserDialog.visible" width="30%" @close="onEditUserDialogClose()">
      <div>
        <el-form
          ref="editUserForm"
          :model="editUserDialog.formData"
          :rules="editUserDialog.formRules"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserDialog.formData.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserDialog.formData.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserDialog.formData.mobile"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="eidtUser()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="assignRoleDialog.visible" width="50%" @close="onAssginRoleDialogClose()">
      <div>
        <p>当前的用户：<span v-text="assignRoleDialog.curUser.username"></span></p>
        <p>当前的角色：<span v-text="assignRoleDialog.curUser.role_name"></span></p>
        <p>
          <span>分配角色：</span>
          <el-select v-model="assignRoleDialog.selectedRoleId" placeholder="请选择角色">
            <el-option v-for="v in assignRoleDialog.roleList" :key="v.id" :label="v.roleName" :value="v.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRoleDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="assignRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserList',
  data() {
    const emailValidator = (rule, value, cb) => {
      if (!/^([a-zA-Z]|[0-9])(\w)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value)) {
        return cb(new Error('请输入正确的邮箱'))
      }
      return cb()
    }

    const mobileValidator = (rule, value, cb) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        return cb(new Error('请输入合法的手机号'))
      }
      cb()
    }

    return {
      assignRoleDialog: {
        visible: false,
        selectedRoleId: null,
        roleList: [],
        curUser: {}
      },
      addUserDialog: {
        visible: false,
        formData: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        formRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 6, message: '长度在 3 ~ 6 个字符之间', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度在 6 ~ 15 个字符之间', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
              validator: emailValidator,
              trigger: 'blur'
            }
          ],
          mobile: [
            { required: true, message: '请输入手机', trigger: 'blur' },
            {
              validator: mobileValidator,
              trigger: 'blur'
            }
          ]
        }
      },
      editUserDialog: {
        visible: false,
        formData: {
          id: 0,
          username: '',
          email: '',
          mobile: ''
        },
        formRules: {
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: emailValidator, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机', trigger: 'blur' },
            { validator: mobileValidator, trigger: 'blur' }
          ]
        }
      },
      searchInputValue: '',
      users: [],
      pageInfo: {
        pagenum: 1,
        pagesize: 2,
        total: 0
      }
    }
  },
  methods: {
    onAssginRoleDialogClose() {
      this.assignRoleDialog.selectedRoleId = null
    },
    async showAssignRoleDialog(user) {
      this.assignRoleDialog.curUser = user
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.assignRoleDialog.roleList = res.data
      this.assignRoleDialog.visible = true
    },
    async assignRole() {
      const { data: res } = await this.$http.put(`users/${this.assignRoleDialog.curUser.id}/role`, {
        rid: this.assignRoleDialog.selectedRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('编辑用户角色失败')
      }
      this.$message.success('更新用户角色成功')
      this.loadUserList()
      this.assignRoleDialog.visible = false
    },
    async removeUser(user) {
      const result = await this.$confirm(`此操作将永久删除用户："${user.username}"，是否继续？`, '提示', {
        type: 'warning'
      }).catch(err => err)

      if (result !== 'confirm') return

      const { data: res } = await this.$http.delete(`/users/${user.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.loadUserList()
    },
    async eidtUser() {
      const ok = await this.$refs.editUserForm.validate().catch(err => err)
      if (!ok) return
      const user = this.editUserDialog.formData
      const { data: res } = await this.$http.put(`/users/${user.id}`, {
        email: user.email,
        mobile: user.mobile
      })
      if (res.meta.status !== 200) {
        return this.$message.error('编辑失败')
      }
      this.$message.success('编辑成功')
      this.editUserDialog.visible = false
      this.loadUserList()
    },
    onEditUserDialogClose() {
      this.$refs.editUserForm.resetFields()
    },
    toEditUser(user) {
      this.editUserDialog.visible = true

      this.editUserDialog.formData.id = user.id
      this.editUserDialog.formData.username = user.username
      this.editUserDialog.formData.email = user.email
      this.editUserDialog.formData.mobile = user.mobile
    },
    async addUser() {
      const ok = await this.$refs.addUserForm.validate().catch(err => err)
      if (!ok) return
      const { data: res } = await this.$http.post('/users', this.addUserDialog.formData)
      if (res.meta.status !== 201) {
        return this.$message.error('添加失败')
      }
      this.$message.success('添加成功')
      this.addUserDialog.visible = false
      this.loadUserList()
    },
    onAddUserDialogClose() {
      this.$refs.addUserForm.resetFields()
    },
    async onSateChange(state, user) {
      const { data: res } = await this.$http.put(`/users/${user.id}/state/${state}`)
      if (res.meta.status !== 200) {
        return this.$message.error('状态修改失败')
      }
      user.mg_state = state
      this.$message.success('状态修改成功')
    },
    onPagesizeChange(pagesize) {
      this.pageInfo.pagesize = pagesize
      this.loadUserList()
    },
    async loadUserList() {
      const { data: res } = await this.$http.get('/users', {
        params: {
          pagenum: this.pageInfo.pagenum,
          pagesize: this.pageInfo.pagesize,
          query: this.searchInputValue
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.users = res.data.users
      this.pageInfo.total = res.data.total
    },
    onPagenumChange(pagenum) {
      this.pageInfo.pagenum = pagenum
      this.loadUserList()
    }
  },
  created() {
    this.loadUserList()
  }
}
</script>
